package com.zs.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.FileChannel;

/**
 * @Authr: Zhangshuqing
 * @Description:
 * @Date: Created in 11:55 2018/4/11
 * @Modified By:
 */
public class Demo1 {

    public void test() throws Exception {
        long start=System.currentTimeMillis();
        File srcFile = new File("E://a.exe");
        FileInputStream inputStream = new FileInputStream(srcFile);
        FileChannel readChannel = inputStream.getChannel();
        File file = new File("E://test.exe");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream outputStream = new FileOutputStream(file);
        FileChannel channel = outputStream.getChannel();
        readChannel.transferTo(0,readChannel.size(),channel);
        readChannel.close();
        channel.close();
        inputStream.close();
        outputStream.close();


      long end=System.currentTimeMillis();
        System.out.println(end-start);


    }

    public void test2() throws Exception{
        long start=System.currentTimeMillis();
        File srcFile=new File("E://a.exe");
        FileInputStream inputStream=new FileInputStream(srcFile);
        FileChannel readChannel=inputStream.getChannel();


        File outFile = new File("E://out.exe");
        if (!outFile.exists()) {
            outFile.createNewFile();
        }
        FileOutputStream outputStream = new FileOutputStream(outFile);
        FileChannel outChannel = outputStream.getChannel();

        ByteBuffer buffer=ByteBuffer.allocate(1024*1024);

        ByteBuffer outBuffer=ByteBuffer.allocate(1024*1024);
        int len=readChannel.read(buffer);
        while (len!=-1){
            buffer.flip();
            while (buffer.hasRemaining()){
                //写数据
                //outBuffer.put(buffer.get()); //一个字节一个字节的读取
                outBuffer.put(buffer);
                outBuffer.flip();
                outChannel.write(outBuffer);
                outBuffer.clear();
            }
            buffer.compact();
            len=readChannel.read(buffer);
            //System.out.println(len);
        }
        outputStream.close();
        inputStream.close();
        outChannel.close();
        readChannel.close();
        long end=System.currentTimeMillis();
        System.out.println(end-start);
    }

    public static void main(String[] args) throws Exception {
        Demo1 demo1 = new Demo1();
        demo1.test2();

    }
}
